package SSM.Chat.Utils;


import SSM.Chat.Domain.Result;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class Token {

    private static final String str = "DRIFT";

    /**
     * @param name 邮箱名
     * @return
     */
    public String setToken(String name) {
        JwtBuilder builder = Jwts.builder();
        String compact = builder.setHeaderParam("typ", "JWT") // 添加头部信息
                .setHeaderParam("alg", "HS256")
                // 添加载荷,可写多个，目前写了两个
                .claim("Mailbox", name)  //  添加邮箱
//                .claim("power", power)  // 添加权限
                .setSubject("xxx")  //  设置主题
                .setExpiration(new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24 ))) // 设置过期时间,此处为一天
                .setId(UUID.randomUUID().toString()) // 设置令牌的唯一值，
                // 设置签名信息
                //SignatureAlgorithm.HS256设置最后的编码，与头部一样，123设置编码的钥匙，最后用这个钥匙进行解密
                .signWith(SignatureAlgorithm.HS256, str)
                .compact();
        return compact;
    }

    public String getToken(String token) {
        if(token==null){
            return   "401";
        }
        JwtParser parser = Jwts.parser();
        JwtParser jwtParser = parser.setSigningKey(str);// 设置签名信息的key


        Jws<Claims> claimsJws = null;
        try {
            claimsJws = jwtParser.parseClaimsJws(token);
        } catch (ExpiredJwtException  e) {
         return   "401";
        }

        Claims body = claimsJws.getBody();
//        String[] strings = new String[5];
//        strings[0]= body.get("Mailbox").toString();
//        System.out.println(body.get("power"));
//        strings[1]=  body.get("power").toString();
//        strings[1]=  body.getExpiration().toString();
        String mailbox = body.get("Mailbox").toString();
        return mailbox;
    }
}
